rm(list = ls())

if (!require("pacman")) install.packages("pacman")
pacman::p_load(tidyverse)

# Load and prepare data
forsa <- read_rds("data/forsa.rds") %>%
    # Filter to relevant sample
    filter(!is.na(vote_afd), !is.na(yob), yob > 1955, yob < 1990, year > 2016) %>%
    # Create factor variables
    mutate(
        men = ifelse(male == 1, "Men", "Women"),
        east = ifelse(east == 1, "East Germany", "West Germany"),
        male_bin = male,
        east_bin = east
    )

# BW
bw_use <- 6

# Create plot
p1 <- ggplot(forsa, aes(
    x = yob, group = factor(male),
    y = vote_afd, color = factor(male)
)) +
    # Add binned means
    stat_summary_bin(
        geom = "point",
        fun = "mean",
        size = 2,
        binwidth = 3,
        position = position_nudge(x = -0.5)
    ) +
    # Add cutoff line
    geom_vline(xintercept = 1970.5, linetype = "dotted") +
    # Add regression lines
    geom_smooth(
        data = forsa,
        aes(x = yob, group = yob > 1970.5, y = vote_afd),
        method = "lm"
    ) +
    # Theme and labels
    theme_bw() +
    theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1)) +
    ylab("AfD support") +
    xlab("Year of birth") +
    facet_grid(east ~ male) +
    scale_x_continuous(breaks = seq(1945, 2000, 5)) +
    theme(legend.position = "none") +
    scale_color_manual(values = c("black", "grey"))

p1
